package com.bnlr.lrparking.appui.mine.mycar;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bnlr.lrparking.constant.LrConstant;
import com.bnlr.lrparking.constant.Urls;
import com.flyco.animation.BounceEnter.BounceTopEnter;
import com.flyco.animation.SlideExit.SlideBottomExit;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.mcxtzhang.swipemenulib.SwipeMenuLayout;
import com.bnlr.lrparking.app.Application;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.base.BaseActivity;
import com.bnlr.lrparking.app.AppConfig;
import com.bnlr.lrparking.model.CarM;
import com.bnlr.lrparking.model.StallListM;
import com.bnlr.lrparking.view.RecyclerItemClickListener;
import com.bnlr.lrparking.util.CommonUtil;
import com.bnlr.lrparking.widget.refresh.RefreshHolderUtil;
import com.bnlr.lrparking.widget.refresh.XRefreshLayout;
import com.bnlr.nohttp.CallServer;
import com.bnlr.nohttp.CustomHttpListener;
import com.yolanda.nohttp.NoHttp;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
/**
 * Created by Administrator on 2017/6/7.
 * 车辆
 */
public class MyCarActivity extends BaseActivity {

    @BindView(R.id.tv_nav_title)
    TextView tvNavTitle;
    @BindView(R.id.iv_nav_back)
    ImageView ivNavBack;
    @BindView(R.id.lv_mycar_list)
    RecyclerView lvMycarList;
    @BindView(R.id.rl_mycar_refresh)
    XRefreshLayout rlMycarRefresh;
    @BindView(R.id.iv_hint)
    ImageView ivHint;
    @BindView(R.id.tv_hint_tips)
    TextView tvHintTips;
    @BindView(R.id.ll_hint)
    LinearLayout llHint;
    static List<CarM.DataBean> myCarList=new ArrayList<>();
    private MyCarAdapter adapter;
    private ImageView iv_nav_right;
    private RelativeLayout rely_add_car;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mycar);
        ButterKnife.bind(this);
        tvNavTitle.setText("我的车辆");
        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        getData();
    }

    private View footView;
    private TextView tv_foot;
    private void initView() {
        iv_nav_right=(ImageView)findViewById(R.id.iv_nav_right);
        iv_nav_right.setImageResource(R.mipmap.add_black);
        rely_add_car=(RelativeLayout)findViewById(R.id.rely_add_car);
        tvHintTips.setText("暂无数据");
        llHint.setVisibility(View.GONE);
        footView = View.inflate(baseContext, R.layout.layout_footview, null);
        tv_foot = (TextView) footView.findViewById(R.id.tv_foot);
        footView.setVisibility(View.GONE);
        linearLayoutManager = new LinearLayoutManager(baseContext);
        lvMycarList.setLayoutManager(linearLayoutManager);
        lvMycarList.setItemAnimator(new DefaultItemAnimator());
        rlMycarRefresh.setRefreshViewHolder(RefreshHolderUtil.getRefreshHolder(this));
        adapter = new MyCarAdapter(baseContext, R.layout.item_mycar, myCarList);
        /*headerAndFooterAdapter = new HeaderAndFooterRecyclerViewAdapter(adapter);
        headerAndFooterAdapter.addFooterView(footView);*/
        lvMycarList.setAdapter(adapter);

        rlMycarRefresh.setDelegate(new XRefreshLayout.BGARefreshLayoutDelegate() {
            @Override
            public void onBGARefreshLayoutBeginRefreshing(XRefreshLayout refreshLayout) {
                footView.setVisibility(View.GONE);
                llHint.setVisibility(View.GONE);
                if (myCarList.size() > 0) {
                    myCarList.clear();
                    adapter.notifyDataSetChanged();
                }
                getData();
            }

            @Override
            public boolean onBGARefreshLayoutBeginLoadingMore(XRefreshLayout refreshLayout) {
                return false;
            }

        });
        rlMycarRefresh.beginRefreshing();
        lvMycarList.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return rlMycarRefresh.isRefreshing();
            }
        });

        lvMycarList.addOnItemTouchListener(
                new RecyclerItemClickListener(baseContext, lvMycarList ,new RecyclerItemClickListener.OnItemClickListener() {
                    @Override public void onItemClick(View view, int position) {
                        // do whatever
                        Intent intent=new Intent(MyCarActivity.this,MyCarDetailsActivity.class);
                        intent.putExtra("carDetail",myCarList.get(position));
                        startActivity(intent);
                    }

                    @Override public void onLongItemClick(View view, int position) {
                        // do whatever
                    }
                })
        );
        iv_nav_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(AddCarActivity.class);
            }
        });
        rely_add_car.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(AddCarActivity.class);
            }
        });
    }

    public void getData() {
        super.getData();
        try {
            mRequest = NoHttp.createStringRequest(Urls.IP, LrConstant.POST);
            mRequest.add("action", "GetCarByUserId");
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            // 添加到请求队列+
            CallServer.getRequestInstance().add(baseContext, mRequest,
                    new CustomHttpListener<CarM>(baseContext, true, CarM.class) {
                        @Override
                        public void doWork(CarM data, String code) {
                            if("1".equals(code)){
//                                myCarList=data.getData();
                                //Log.e("车辆列表", data.getData().get(data.getData().size()-1).toString());
                                myCarList.clear();
                                myCarList.addAll(data.getData());
                                adapter.notifyDataSetChanged();
                            }
                        }

                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            try {
                                super.onFinally(obj, code, isSucceed);
                                if (rlMycarRefresh != null ){
                                    rlMycarRefresh.endRefreshing();
                                }
                                isLoadingMore = false;
                                if (myCarList.size()==0){
                                    llHint.setVisibility(View.VISIBLE);
                                    rely_add_car.setVisibility(View.VISIBLE);
                                    ivHint.setBackgroundResource(R.mipmap.empty_nocar);
                                    tvHintTips.setText("您还没有添加车辆信息哦~添加您的车辆信息，在支持自动付费的停车场停车，无需操作，系统自动结算。");
                                    myCarList.clear();
                                    adapter.notifyDataSetChanged();
                                }else {
                                    llHint.setVisibility(View.GONE);
                                    if (!TextUtils.equals("1", code)) {
                                        footView.setVisibility(View.VISIBLE);
                                        tv_foot.setText(R.string.foot_all);
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, false);
        } catch (Exception e) {

        }
    }
    public  class MyCarAdapter extends CommonAdapter<CarM.DataBean>{

        public MyCarAdapter(Context context, int layoutId, List<CarM.DataBean> datas) {
            super(context, layoutId, datas);
        }

        @Override
        protected void convert(final ViewHolder holder, final CarM.DataBean s, int position) {
            SwipeMenuLayout car_swipe=holder.getView(R.id.car_swipe);
            Button car_btnDel=holder.getView(R.id.car_btnDel);
            if(position==myCarList.size()-1){
                holder.setVisible(R.id.line01,false);
            }else{
                holder.setVisible(R.id.line01,true);
            }
            holder.setText(R.id.mycar_num,s.getCarNum());
            if (s.getStatus().equals("1")){
                holder.setText(R.id.car_check,"已审核");
                holder.setTextColorRes(R.id.car_check,R.color.main_color);
                holder.setImageResource(R.id.img_car_check,R.mipmap.icon_me_check3);
                car_swipe.setSwipeEnable(false);
            }else if (s.getStatus().equals("2")){
                holder.setText(R.id.car_check,"审核中");
                holder.setTextColorRes(R.id.car_check,R.color.gray03_color);
                holder.setImageResource(R.id.img_car_check,R.mipmap.icon_me_check1);
                car_swipe.setSwipeEnable(false);
            }else if (s.getStatus().equals("3")){
                holder.setText(R.id.car_check,"审核失败");
                holder.setTextColorRes(R.id.car_check,R.color.order_type);
                holder.setImageResource(R.id.img_car_check,R.mipmap.icon_me_check2);
                car_swipe.setSwipeEnable(true);
            }
            car_btnDel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final NormalDialog dialog = new NormalDialog(baseContext);
                    dialog.title("提示")
                            .titleTextColor(baseContext.getResources().getColor(R.color.black_color))
                            .titleTextSize(15)
                            .content("是否删除此车辆？")
                            .contentTextSize(15)
                            .contentTextColor(baseContext.getResources().getColor(R.color.gray_color))
                            .btnText("取消", "确定")
                            .btnNum(2)
                            .style(NormalDialog.STYLE_TWO)
                            .btnTextColor(baseContext.getResources().getColor(R.color.gray_color), baseContext.getResources().getColor(R.color.colorAccent))
                            .btnTextSize(15, 15)
                            .widthScale(0.8f)//
                            .showAnim(new BounceTopEnter())//
                            .dismissAnim(new SlideBottomExit())//
                            .cornerRadius(7)
                            .show();
                    dialog.setCancelable(true);
                    dialog.setOnBtnClickL(
                            new OnBtnClickL() {
                                @Override
                                public void onBtnClick() {
                                    dialog.dismiss();
                                }
                            },
                            new OnBtnClickL() {
                                @Override
                                public void onBtnClick() {
                                    dialog.dismiss();
                                    getDeleteCar(s.getId());
                                    myCarList.clear();
                                    adapter.notifyDataSetChanged();
                                }
                            });
                }
            });
        }
    }

    //删除车辆
    private void getDeleteCar(String id){
        try {
            mRequest = NoHttp.createStringRequest(Urls.CAR_IP, LrConstant.POST);
            mRequest.add("action", "DeleteCar");
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("id",id);

            CallServer.getRequestInstance().add(baseContext, mRequest,
                    new CustomHttpListener<StallListM>(baseContext, true, StallListM.class) {
                        @Override
                        public void doWork(StallListM data, String code) {
                            if (code.equals("1")) {
                                getData();
                                adapter.notifyDataSetChanged();
                            }else {
                                CommonUtil.showToask(MyCarActivity.this,data.getMsg());
                            }
                        }
                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            try {
                                super.onFinally(obj, code, isSucceed);
                                if (code.equals("1")) {
                                }else {
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, false);
        } catch (Exception e) {

        }
    }
}
